package com.xinling.modules.user.controller;

import com.xinling.common.api.ApiResult;
import com.xinling.modules.user.model.dto.LoginDTO;
import com.xinling.modules.user.model.dto.RegisterDTO;
import com.xinling.modules.user.model.vo.UserVO;
import com.xinling.modules.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

@Api(tags = "用户接口")
@RestController
@RequestMapping("/auth")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ApiResult<UserVO> register(@Valid @RequestBody RegisterDTO registerDTO) {
        UserVO userVO = userService.register(registerDTO);
        return ApiResult.success(userVO);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ApiResult<String> login(@Valid @RequestBody LoginDTO loginDTO) {
        String isLogin = userService.login(loginDTO);
        if(isLogin=="-1"){
            return ApiResult.failed("用户不存在");
        }
        if(isLogin=="-2"){
            return ApiResult.failed("密码错误");
        }

        return ApiResult.success(isLogin);
    }

    @ApiOperation("获取当前用户信息")
    @GetMapping("/info")
    public ApiResult<UserVO> getUserInfo() {
        UserVO userVO = userService.getCurrentUser();
        return ApiResult.success(userVO);
    }

    @ApiOperation("更新用户信息")
    @PutMapping("/info")
    public ApiResult<UserVO> updateUserInfo(@RequestBody UserVO userVO) {
        UserVO updated = userService.updateUserInfo(userVO);
        return ApiResult.success(updated);
    }

    @ApiOperation("修改密码")
    @PutMapping("/password")
    public ApiResult<Void> updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
        userService.updatePassword(oldPassword, newPassword);
        return ApiResult.success();
    }

    @ApiOperation("上传头像")
    @PostMapping("/avatar")
    public ApiResult<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        String url = userService.uploadAvatar(file);
        return ApiResult.success(url);
    }
} 